package org.squirrel.modules.system.auth.request;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.enums.AuthResponseStatus;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.log.Log;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthDefaultRequest;
import me.zhyd.oauth.utils.AuthChecker;
@Slf4j
public abstract class BaseAuthRequest extends AuthDefaultRequest {

	public BaseAuthRequest(AuthConfig config, AuthSource source) {
		super(config, source);
	}

	public BaseAuthRequest(AuthConfig config, AuthSource source, AuthStateCache authStateCache) {
		super(config, source, authStateCache);
	}
	
	@Override
	public AuthResponse login(AuthCallback authCallback) {
		try {
			AuthChecker.checkCode(source, authCallback);
			if (!config.isIgnoreCheckState()) {
				AuthChecker.checkState(authCallback.getState(), source, authStateCache);
			}

			AuthToken authToken = this.getAccessToken(authCallback);
			AuthUser user = this.getUserInfo(authToken);
			return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).data(user).build();
		} catch (Exception e) {
			Log.error("Failed to login with oauth authorization.", e);
			return this.responseError(e);
		}
	}
	
	protected AuthResponse responseError(Exception e) {
		int errorCode = AuthResponseStatus.FAILURE.getCode();
		String errorMsg = e.getMessage();
		if (e instanceof AuthException) {
			AuthException authException = ((AuthException) e);
			errorCode = authException.getErrorCode();
			if (StringUtils.isNotEmpty(authException.getErrorMsg())) {
				errorMsg = authException.getErrorMsg();
			}
		}
		return AuthResponse.builder().code(errorCode).msg(errorMsg).build();
	}
	
	protected void checkResponseIsBlank(JSONObject object,String obj) {
		if (StringUtils.isBlank(object.getString(obj))) {
			log.error("获取数据:{}为空",obj);
			throw new AuthException("获取数据为空异常");
		}
	}
	
	protected void checkResponseEquals(String status,String expectValue) {
		if (!StringUtils.equals(status, expectValue)) {
			log.error("响应状态不成功,status:{}",status);
			throw new AuthException("响应状态不成功");
		}
	}
}
